<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
  >
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
      <el-form-item label="话题" prop="topicId">
        <el-select v-model="dataForm.topicId" placeholder="请选择话题" :disabled="!!defaultTopicId">
          <el-option
            v-for="item in topicOptions"
            :key="item.topicId"
            :label="item.title"
            :value="item.topicId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="动态ID" prop="postId">
        <el-input v-model="dataForm.postId" placeholder="请输入动态ID"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'TopicParticipationsAddOrUpdate',
  data () {
    return {
      visible: false,
      defaultTopicId: '',
      topicOptions: [],
      dataForm: {
        topicId: '',
        postId: ''
      },
      dataRule: {
        topicId: [
          { required: true, message: '话题不能为空', trigger: 'change' }
        ],
        postId: [
          { required: true, message: '动态ID不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init (topicId) {
      this.defaultTopicId = topicId
      this.dataForm.topicId = topicId
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        // 获取话题列表
        if (!this.defaultTopicId) {
          this.getTopicList()
        }
      })
    },
    // 获取话题列表
    getTopicList () {
      this.$http({
        url: this.$http.adornUrl('/community/hot-topics/all'),
        method: 'get'
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.topicOptions = data.list
        }
      })
    },
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/community/topic-participations/save'),
            method: 'post',
            data: this.$http.adornData({
              'topicId': this.dataForm.topicId,
              'postId': this.dataForm.postId
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script> 